package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.DishDto;
import com.itheima.entity.DishFlavor;
import com.itheima.mapper.DishMapper;
import com.itheima.entity.Dish;
import com.itheima.service.DishFlaverService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.stream.Collectors;

/**
 * @email 1572178030@qq.com
 * @author:黄海宾
 * @date: 2023/2/4  15:55
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlaverService dishFlaverService;


    //添加菜单
    @Override
    public void dishWithFlaver(DishDto dishDto) {
        /*
         * 保存二个数据 一个保存在Dish中
         * 还有一个保存在DishFlaver中
         * 找到该数据，要为其中赋值id
         * 直接保存会缺少id
         * 保存到dishFlaver中
         * */
        //保存到对应的dish中
        this.save(dishDto);
        //为了给保存到flaver中赋对应dish的id
        Long flaverId = dishDto.getId();

        //得到disDto中的flaver值
        List<DishFlavor> flavers = dishDto.getFlavors();

        List<DishFlavor> listFlaver = flavers.stream().map(item -> {
            //一个一个得到id中赋予Dish的id
            item.setDishId(flaverId);
            return item;
        }).collect(Collectors.toList());

        dishFlaverService.saveBatch(listFlaver);
    }

    /*
    修改菜品数据
    * */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        Dish dish = this.getById(id);

        log.info("通过id查到的数{}", dish);
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish, dishDto);

        log.info("dishDto{}", dishDto);
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dish.getId());//select * from dishFlaver where  id= id;

        List<DishFlavor> favers = dishFlaverService.list(dishFlavorLambdaQueryWrapper);
        log.info("数据{}", favers);

        dishDto.setFlavors(favers);
        return dishDto;
    }



}
